package com.xunqi.content.controller;

import com.github.pagehelper.PageInfo;
import com.xunqi.common.auth.CheckLogin;
import com.xunqi.common.dto.content.ShareDTO;
import com.xunqi.common.entity.content.Share;
import com.xunqi.common.util.JwtOperator;
import com.xunqi.content.service.ShareService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-17 11:02
 **/
@RestController
@RequestMapping(value = "/shares")
public class ShareController {

    @Resource
    private ShareService shareService;

    @Resource
    private JwtOperator jwtOperator;

    @GetMapping(value = "/{id}")
    @CheckLogin
    public ShareDTO findById(@PathVariable("id") Integer id) {
        return shareService.findById(id);
    }


    @GetMapping(value = "/q")
    public PageInfo<Share> q(@RequestParam(required = false) String title,
                             @RequestParam(required = false,defaultValue = "1")Integer pageNo,
                             @RequestParam(required = false,defaultValue = "10")Integer pageSize,
                             @RequestParam(required = false,value = "X-Token")String token){

        //注意：pageSize必做控制
        if (pageSize > 100) {
            pageSize = 100;
        }

        if (token.equals("[object Undefined]")) {
            token = null;
        }

        Integer userId = null;

        if (StringUtils.isNotBlank(token)) {
            Claims claims = jwtOperator.getClaimsFromToken(token);
            userId = (Integer)claims.get("id");
        }

        //根据查询条件分页获取数据
        PageInfo<Share> pageInfoList = this.shareService.q(title, pageNo, pageSize, userId);

        return pageInfoList;
    }

    @GetMapping(value = "/exchange/{id}")
    @CheckLogin
    public Share exchangeById(@PathVariable("id") Integer id, HttpServletRequest request) {
        return this.shareService.exchangeById(id,request);
    }
}
